package com.sea.base.ext.global

import android.text.TextUtils
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone

const val HOUR_MILLIS = 3_600_000
const val DAY_MILLIS = HOUR_MILLIS * 24

inline val Number.hourMillis get() = (this.toFloat() * HOUR_MILLIS).toLong()
inline val Number.daysMillis get() = (this.toFloat() * DAY_MILLIS).toLong()

val YMD = "yyyy-MM-dd"
val YMDHMS = "yyyy-MM-dd HH:mm:ss"
val YMDHM_C = "yyyy年MM月dd日 HH:mm"
val YMDHMSS = "yyyy-MM-dd HH:mm:ss.SSS"

@Suppress("NOTHING_TO_INLINE")
inline fun Long.toDateString(pattern: String = YMDHMS): String {
    return SimpleDateFormat(pattern, Locale.getDefault(Locale.Category.FORMAT)).format(Date(this))
}

/**
 * 安全的转换，如果失败则为[defValue]
 */
@Suppress("NOTHING_TO_INLINE")
@JvmOverloads
inline fun String?.safeParseDateFormat(pattern: String = YMDHMS, defValue: Long = 0L): Long {
    if (TextUtils.isEmpty(this)) return defValue
    return try {
        SimpleDateFormat(pattern, Locale.getDefault(Locale.Category.FORMAT)).parse(this ?: return defValue)?.time ?: defValue
    } catch (e: Throwable) {
        e.printStackTrace()
        defValue
    }
}

inline val Long.isToday get() = dayDifferent == 0

/**
 * 距今相差多少天
 * 负数：昨天、前天……
 * 0：今天
 * 正数：明天、后天……
 */
inline val Long.dayDifferent: Int
    get() {
        val offset = TimeZone.getDefault().rawOffset
        val day = (this + offset) / (1.daysMillis)
        val nowDay = (getCurrentMillis() + offset) / (1.daysMillis)
        return (day - nowDay).toInt()
    }

/**
 * 推荐的时间展示
 */
@Suppress("NOTHING_TO_INLINE")
inline fun Long.toSuggestDateDesc() = smartFormatTime()

inline val Int.toTimeAddZero get() = if (this < 10) "0$this" else this.toString()